package com.weiyi.mashangzhu.Roomer.Activity;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.weiyi.mashangzhu.API.API;
import com.weiyi.mashangzhu.Application.MyApp;
import com.weiyi.mashangzhu.Base.BaseActivity;
import com.weiyi.mashangzhu.R;
import com.weiyi.mashangzhu.Roomer.Bean.OrderDetailsBean;
import com.weiyi.mashangzhu.Utils.GlideImgManager;
import com.weiyi.mashangzhu.Utils.LoadingDialog;
import com.weiyi.mashangzhu.Utils.SPUtils;
import com.weiyi.mashangzhu.Utils.T;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class OrderDetailActivity extends BaseActivity {


    @BindView(R.id.order_detail_status)
    TextView orderDetailStatus;
    @BindView(R.id.order_detail_id)
    TextView orderDetailId;
    @BindView(R.id.order_detail_img)
    ImageView orderDetailImg;
    @BindView(R.id.order_detail_title)
    TextView orderDetailTitle;
    @BindView(R.id.order_detail_type)
    TextView orderDetailType;
    @BindView(R.id.order_detail_price)
    TextView orderDetailPrice;
    @BindView(R.id.order_detail_address)
    TextView orderDetailAddress;
    @BindView(R.id.order_detail_time)
    TextView orderDetailTime;
    @BindView(R.id.order_detail_earnest)
    TextView orderDetailEarnest;
    @BindView(R.id.order_detail_money)
    TextView orderDetailMoney;
    @BindView(R.id.order_detail_sum)
    TextView orderDetailSum;
    @BindView(R.id.order_detail_coupon)
    RelativeLayout orderDetailCoupon;
    @BindView(R.id.order_detail_name)
    TextView orderDetailName;
    @BindView(R.id.order_detail_number)
    TextView orderDetailNumber;
    @BindView(R.id.order_detail_create_time)
    TextView orderDetailCreateTime;
    @BindView(R.id.order_detail_contact)
    Button orderDetailContact;
    @BindView(R.id.order_detail_amount)
    TextView orderDetailAmount;
    @BindView(R.id.order_detail_pay)
    Button orderDetailPay;
    @BindView(R.id.back)
    ImageView back;
    String type = "";
    String id;
    @BindView(R.id.bottom)
    LinearLayout bottom;
    List<OrderDetailsBean.DataBean.CouponlistBean> couponlistBeanList = new ArrayList<>();
    OrderDetailsBean.DataBean.HouseBean houseBean;
    OrderDetailsBean.DataBean.OrderBean orderBean;
    OrderDetailsBean orderDetailsBean;
    @BindView(R.id.coupon)
    TextView coupon;
    IWXAPI msgApi;
    String phone_fk, phone_fd;
    int coupon_id = -1;
    public static OrderDetailActivity intence = null;
    String url = "";
    String cQuotav, cPrice;
    @BindView(R.id.next)
    ImageView next;
    String status="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);
        ButterKnife.bind(this);
        intence = this;

        Intent intent = getIntent();
        type = intent.getStringExtra("info");
        id = intent.getStringExtra("id");
        status=intent.getStringExtra("status");
        Log.e("ppppppppp", "===" + id);
        Log.e("ppppppppp", "===" + type);

        if (type.equals("1")) {
            orderDetailId.setVisibility(View.GONE);
            bottom.setVisibility(View.GONE);
            orderDetailContact.setText("联系房客");
            cQuotav = intent.getStringExtra("cQuota");
            cPrice = intent.getStringExtra("cPrice");
            Log.e("ppppppppp", "===" + cQuotav);
            Log.e("ppppppppp", "===" + cPrice);
            if (cQuotav != null && cPrice != null && !cQuotav.equals("") && !cPrice.equals("")) {
                coupon.setText("满" + cQuotav + "减" + cPrice);
                next.setVisibility(View.INVISIBLE);
                orderDetailCoupon.setVisibility(View.VISIBLE);
            }
            else {
                orderDetailCoupon.setVisibility(View.GONE);
            }
            url = API.BaseApi_L;
        } else {
            url = API.BaseApi_R;
            if (type.equals("0")) {
                orderDetailContact.setText("联系房东");
                orderDetailId.setVisibility(View.VISIBLE);
                orderDetailCoupon.setVisibility(View.VISIBLE);
                bottom.setVisibility(View.VISIBLE);
            } else {
                orderDetailContact.setText("联系房东");
                orderDetailId.setVisibility(View.GONE);
                orderDetailCoupon.setVisibility(View.VISIBLE);
                bottom.setVisibility(View.GONE);
            }


        }
        LoadingDialog.show(this);
        OkHttpUtils.get()
                .addParams("token", SPUtils.get(this, "token", "") + "")
                .addParams("id", id)
                .url(url + API.OrderDetails)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        LoadingDialog.dismiss(OrderDetailActivity.this);
                        T.showShort(OrderDetailActivity.this, "数据获取失败，请稍后再试");
                    }

                    @Override
                    public void onResponse(String response) {
                        Log.e("orrrrrrrrr", "==" + response);
                        Log.e("orrrrrrr", "==" + couponlistBeanList.size());
                        LoadingDialog.dismiss(OrderDetailActivity.this);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.getInt("status") == 0) {
                                orderDetailsBean = new Gson().fromJson(response, OrderDetailsBean.class);
                                //获取房客和房东的手机号
                                phone_fd = orderDetailsBean.getData().getUAccountfd();
                                phone_fk = orderDetailsBean.getData().getUAccountfk();
//                                if (type.equals("1")) {
//                                    String status = "";
//                                    if (orderDetailsBean.getData().getOrder().getOStatus() == 0) {
//                                        status = "待接单";
//                                    } else if (orderDetailsBean.getData().getOrder().getOStatus() == 1) {
//                                        status = "待付款";
//                                    } else if (orderDetailsBean.getData().getOrder().getOStatus() == 2) {
//                                        status = "待入住";
//                                    } else if (orderDetailsBean.getData().getOrder().getOStatus() == 3) {
//                                        status = "入住中";
//                                    } else if (orderDetailsBean.getData().getOrder().getOStatus() == 4) {
//                                        status = "已完成";
//                                    } else if (orderDetailsBean.getData().getOrder().getOStatus() == 5) {
//                                        status = "退款中";
//                                    } else if (orderDetailsBean.getData().getOrder().getOStatus() == 6) {
//                                        status = "已退款";
//                                    } else if (orderDetailsBean.getData().getOrder().getOStatus() == 7) {
//                                        status = "收款中";
//                                    } else if (orderDetailsBean.getData().getOrder().getOStatus() == 8) {
//                                        status = "已收款";
//                                    }else if (orderDetailsBean.getData().getOrder().getOStatus() == 10) {
//                                        status = "已评价";
//                                    }
//                                    orderDetailStatus.setText(status);
//                                } else {
//                                    String status = "";
//                                    if (orderDetailsBean.getData().getOrder().getOStatus() == 0) {
//                                        status = "待接单";
//                                    } else if (orderDetailsBean.getData().getOrder().getOStatus() == 1) {
//                                        status = "待付款";
//                                    } else if (orderDetailsBean.getData().getOrder().getOStatus() == 2) {
//                                        status = "待入住";
//                                    } else if (orderDetailsBean.getData().getOrder().getOStatus() == 3) {
//                                        status = "入住中";
//                                    } else if (orderDetailsBean.getData().getOrder().getOStatus() == 4) {
//                                        status = "待评价";
//                                    } else if (orderDetailsBean.getData().getOrder().getOStatus() == 5) {
//                                        status = "退款中";
//                                    } else if (orderDetailsBean.getData().getOrder().getOStatus() == 6) {
//                                        status = "已退款";
//                                    } else if (orderDetailsBean.getData().getOrder().getOStatus() == 7) {
//                                        status = "收款中";
//                                    } else if (orderDetailsBean.getData().getOrder().getOStatus() == 8) {
//                                        status = "已收款";
//                                    }
                                    orderDetailStatus.setText(status);
//                                }

                                if (orderDetailsBean != null) {
                                    orderDetailId.setText(orderDetailsBean.getData().getUNickname() + "");
                                    couponlistBeanList.clear();
                                    for (int i = 0; i < orderDetailsBean.getData().getCouponlist().size(); i++) {
                                        couponlistBeanList.addAll(orderDetailsBean.getData().getCouponlist().get(i));

                                    }
                                    Log.e("orrrrrrrrrr", "size=" + orderDetailsBean.getData().getCouponlist().size());
                                    if (!type.equals("1")){
                                        switch (orderDetailsBean.getData().getCouponlist().size()) {
                                            case 0:
                                                coupon.setVisibility(View.VISIBLE);
                                                coupon.setText("无");
                                                break;
                                            case 1:
                                                coupon.setVisibility(View.VISIBLE);
                                                coupon.setText("满" + couponlistBeanList.get(0).getCQuota() + "减" + couponlistBeanList.get(0).getCPrice());
                                                break;
                                            case 2:
                                                MyApp.couponlistBeanList_yes = orderDetailsBean.getData().getCouponlist().get(0);
                                                MyApp.couponlistBeanList_no = orderDetailsBean.getData().getCouponlist().get(1);
                                                coupon.setVisibility(View.GONE);
                                                break;
                                        }
                                    }
                                    houseBean = orderDetailsBean.getData().getHouse();
                                    orderBean = orderDetailsBean.getData().getOrder();
                                    if (houseBean != null) {
                                        GlideImgManager.glideLoader(OrderDetailActivity.this, API.BaseApi_url + houseBean.getHImg1(), R.mipmap.errer, orderDetailImg);
                                        orderDetailTitle.setText(houseBean.getHTitle());
                                        orderDetailType.setText(houseBean.getHRoom() + "居室");
                                        orderDetailPrice.setText("¥" + houseBean.getHPrice() + "/每晚");
                                        orderDetailAddress.setText(houseBean.getHProvince() + houseBean.getHCity() + houseBean.getHDistrict() + houseBean.getHAddress());
                                    }
                                    if (orderBean != null) {
                                        orderDetailTime.setText("入住期:" + orderBean.getOLivetime() + "-" + orderBean.getOCheckouttime());
                                        orderDetailEarnest.setText("¥" + orderBean.getODeposit());
                                        orderDetailMoney.setText("¥" + orderBean.getOPrice());
                                        orderDetailSum.setText("¥" + orderBean.getOTotalPrice());
                                        orderDetailName.setText(orderBean.getUserName());
                                        orderDetailNumber.setText(orderBean.getONum());
                                        orderDetailCreateTime.setText(orderBean.getOTime());
                                        orderDetailAmount.setText("¥" + orderBean.getOTotalPrice());
                                    }

                                }
                            } else {
                                T.showShort(OrderDetailActivity.this, jsonObject.getString("msg"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                });
    }

    @Override
    public void initView() {
        super.initView();

    }

    @Override
    protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x001 && data != null) {
            if (resultCode == 0x002) {
                final double price = data.getDoubleExtra("CPrice", 0);
                final double CQuota = data.getDoubleExtra("CQuota", 0);
                coupon_id = data.getIntExtra("id", -1);

                //提交优惠券id 修改价格
                OkHttpUtils.get()
                        .addParams("token", SPUtils.get(OrderDetailActivity.this, "token", "") + "")
                        .addParams("id", id)
                        .addParams("couponId", coupon_id + "")
                        .url(API.BaseApi_R + API.UpdateOrderbycoun)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Request request, Exception e) {
                                T.showShort(OrderDetailActivity.this, "数据获取失败，请稍后再试");
                            }

                            @Override
                            public void onResponse(String response) {
                                Log.e("mmmmmmmmmmmmmmmmmm", "=" + response);
                                if (response != null) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        if (jsonObject != null) {
                                            if (jsonObject.getInt("status") == 0) {
                                                coupon.setVisibility(View.VISIBLE);
                                                coupon.setText("满" + CQuota + "减" + price);
                                                orderDetailAmount.setText("¥" + jsonObject.getJSONObject("data").getDouble("oTotalPrice"));
                                            } else {
                                                T.showShort(OrderDetailActivity.this, jsonObject.getString("msg"));
                                            }
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }

                            }
                        });
            }
        }
    }

    @Override
    public void permissionSuccess(int requestCode) {
        super.permissionSuccess(requestCode);
        switch (requestCode) {
            case 0x004:
                if (type.equals("1")) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_CALL);
                    intent.setData(Uri.parse("tel:" + phone_fk));
                    startActivity(intent);
                } else {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_CALL);
                    intent.setData(Uri.parse("tel:" + phone_fd));
                    startActivity(intent);
                }
                break;
        }
    }

    @OnClick({R.id.back, R.id.order_detail_coupon, R.id.order_detail_contact, R.id.order_detail_pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.order_detail_coupon:
                if (type.equals("1")){

                }else {
                    switch (orderDetailsBean.getData().getCouponlist().size()) {

                        case 0:
                            break;
                        case 1:
                            break;
                        case 2:
                            Intent intent = new Intent(this, CouponActivity.class);
                            intent.putExtra("info", "order");
                            startActivityForResult(intent, 0x001);
                            break;
                }

                }

                break;
            case R.id.order_detail_contact:
                if (type.equals("1")) {
                    //联系房客
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        requestPermission(new String[]{Manifest.permission.CALL_PHONE}, 0x004);
                    } else {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_CALL);
                        intent.setData(Uri.parse("tel:" + phone_fk));
                        startActivity(intent);
                    }
                } else {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        requestPermission(new String[]{Manifest.permission.CALL_PHONE}, 0x004);
                    } else {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_CALL);
                        intent.setData(Uri.parse("tel:" + phone_fd));
                        startActivity(intent);
                    }
                }

                break;
            case R.id.order_detail_pay:
                LoadingDialog.show(OrderDetailActivity.this);
                Log.e("ppppppppppppp", "=" + SPUtils.get(OrderDetailActivity.this, "token", "") + "");
                Log.e("ppppppppppppp", "=" + coupon_id);
                if (coupon_id == -1) {
                    //未使用优惠券
                    OkHttpUtils.get()
                            .addParams("token", SPUtils.get(OrderDetailActivity.this, "token", "") + "")
                            .addParams("id", id)
                            .url(API.BaseApi_R + API.Pay)
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Request request, Exception e) {
                                    T.showShort(OrderDetailActivity.this, "数据获取失败，请稍后再试");
                                    LoadingDialog.dismiss(OrderDetailActivity.this);
                                }

                                @Override
                                public void onResponse(String response) {
                                    Log.e("ppppppppppppp", "=" + response);
                                    LoadingDialog.dismiss(OrderDetailActivity.this);
//                                        if (response != null) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        msgApi = WXAPIFactory.createWXAPI(OrderDetailActivity.this, null);
                                        msgApi.registerApp("wx29a520b1867fe3a2");
                                        PayReq payReq = new PayReq();
                                        payReq.appId = jsonObject.getString("appid");
                                        payReq.partnerId = jsonObject.getString("partnerid");
                                        payReq.prepayId = jsonObject.getString("prepayid");
                                        payReq.packageValue = jsonObject.getString("package");
                                        payReq.nonceStr = jsonObject.getString("noncestr");
                                        payReq.timeStamp = jsonObject.getString("timestamp");
                                        payReq.sign = jsonObject.getString("sign");
                                        Log.e("ppppppppppppp", msgApi.sendReq(payReq) + "");

                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                } else {
                    Log.e("ppppppppppppp", coupon_id + "");
                    OkHttpUtils.get()
                            .addParams("token", SPUtils.get(OrderDetailActivity.this, "token", "") + "")
                            .addParams("couponId", coupon_id + "")
                            .addParams("id", id)
                            .url(API.BaseApi_R + API.Pay)
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Request request, Exception e) {
                                    T.showShort(OrderDetailActivity.this, "数据获取失败，请稍后再试");
                                    LoadingDialog.dismiss(OrderDetailActivity.this);
                                }

                                @Override
                                public void onResponse(String response) {
                                    Log.e("ppppppppppppp", "=" + response);
                                    LoadingDialog.dismiss(OrderDetailActivity.this);
//                                        if (response != null) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        msgApi = WXAPIFactory.createWXAPI(OrderDetailActivity.this, null);
                                        msgApi.registerApp("wx29a520b1867fe3a2");
                                        PayReq payReq = new PayReq();
                                        payReq.appId = jsonObject.getString("appid");
                                        payReq.partnerId = jsonObject.getString("partnerid");
                                        payReq.prepayId = jsonObject.getString("prepayid");
                                        payReq.packageValue = jsonObject.getString("package");
                                        payReq.nonceStr = jsonObject.getString("noncestr");
                                        payReq.timeStamp = jsonObject.getString("timestamp");
                                        payReq.sign = jsonObject.getString("sign");
                                        Log.e("ppppppppppppp", msgApi.sendReq(payReq) + "");

                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                }

                break;
        }
    }
}
